import datetime

from django.contrib.auth.models import AbstractUser
from django.db import models


class User(AbstractUser):
    """
    用户的基本信息表
    """
    name = models.CharField(max_length=30, unique=True, verbose_name="姓名",
                            null=True, blank=True,
                            error_messages={
                                'unique': '姓名已经在系统中存在'
                            })
    email = models.EmailField(max_length=100, verbose_name="邮箱",
                              unique=True,
                              error_messages={
                                  'unique': '邮箱已经在系统中存在'
                              })
    avatar = models.ImageField(verbose_name='用户头像', upload_to='avatar/', null=True, blank=True)
    valid_date = models.DateField(verbose_name='有效期', default=datetime.date.today)
    invalid_date = models.DateField(verbose_name='失效期')
    # 用户类型分为普通用户和接口用户，接口用户不能登录本系统
    USER_TYPE = (('A', '普通用户'), ('I', '接口用户'))
    user_type = models.CharField(verbose_name='用户类型', max_length=1, choices=USER_TYPE, default='A')
    # 用户初次登录系统、密码被重置时init_status=True，正常为False
    init_status = models.BooleanField(verbose_name='初始状态', default=True)
    roles = models.ManyToManyField('rbac.Role', verbose_name='拥有的所有角色', related_name='roles', blank=True)
    menu_sensitive_fields = models.ManyToManyField('rbac.MenuSensitiveField', verbose_name='拥有的菜单敏感字段',
                                                   related_name='menu_sensitive_fields', blank=True,
                                                   through='rbac.UserMenuSensitiveField')

    class Meta:
        db_table = 'users'
        verbose_name = '用户管理'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username

    def is_admin(self):
        """
        用户绑定管理员角色，则改用户属于管理员
        调用方式：user.is_admin()
        """
        return self.roles.filter(is_admin=True).exists()


class SystemSettings(models.Model):
    code = models.CharField('系统设定代码', max_length=128, unique=True)
    value = models.CharField('系统设定值', max_length=128)
    value_type = models.CharField('系统设定值的数据类型', max_length=32)
    content = models.CharField('系统设定说明', max_length=128, blank=True, null=True)
    is_active = models.BooleanField('系统设定是否有效', default=True)

    class Meta:
        db_table = "system_settings"
        verbose_name = "系统参数设定表"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.code


class UserPasswordHistory(models.Model):
    user = models.ForeignKey(User, verbose_name='用户', related_name='+', on_delete=models.DO_NOTHING)
    md5_password = models.CharField(verbose_name='MD5加密后的密码', max_length=128)
    created_date = models.DateTimeField(verbose_name='新建时间', auto_now_add=True)

    class Meta:
        db_table = 'user_password_history'
        verbose_name = '用户历史密码表'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.user.username


class ExternalSystemAPIWhiteList(models.Model):
    REQUEST_METHOD = (
        ('GET', 'GET方法'),
        ('POST', 'POST方法'),
        ('PUT', 'PUT方法'),
        ('DELETE', 'DELETE方法')
    )
    user = models.ForeignKey(to=User, verbose_name='API接口用户', related_name='+', on_delete=models.DO_NOTHING)
    api_method = models.CharField(verbose_name='接口方法', max_length=20, choices=REQUEST_METHOD)
    api_address = models.CharField(verbose_name='接口地址', max_length=400)
    api_description = models.CharField(verbose_name='接口说明', max_length=400, blank=True, null=True)

    class Meta:
        db_table = 'external_system_api_white_list'
        verbose_name = '外部系统接口表'
        verbose_name_plural = verbose_name
